import React, { useEffect, useRef } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import './index.scss'
const MapComponent = () => {
  // { mapKey, mapContainerId, mapOptions }
  const mapContainerRef = useRef(null);
  // const passedPolylineRef = useRef(null);
  const mapKey = '75876dfd8041f621bea17fc75c4effd8';
  const mapContainerId = 'mapContainer';
  const mapOptions = {
    zoom: 10,
    center: [116.397428, 39.90923], // 初始化地图中心点坐标
  };

  const mapRef = useRef(null);
  const markerRef = useRef(null);
  const passedPolylineRef = useRef(null);
  useEffect(() => {
    // createMap()
    AMapLoader.load({
      key: '75876dfd8041f621bea17fc75c4effd8', // 替换为您的高德地图API key
      version: '2.0',
      plugins: ['AMap.MoveAnimation'],
    }).then((AMap) => {
      const map = new AMap.Map(mapRef.current, {
        resizeEnable: true,
        center: [116.397428, 39.90923],
        zoom: 17,
      });

      const marker = new AMap.Marker({
        map: map,
        position: [116.478935, 39.997761],
        icon: 'https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png',
        offset: new AMap.Pixel(-13, -26),
      });

      const lineArr = [
        [116.478935, 39.997761],
        [116.478939, 39.997825],
        // ... 其他坐标点
        [116.482362, 39.997718],
        [116.483633, 39.998935],
      ];

      const polyline = new AMap.Polyline({
        map: map,
        path: lineArr,
        showDir: true,
        strokeColor: '#28F',
        strokeWeight: 6,
      });

      const passedPolyline = new AMap.Polyline({
        map: map,
        strokeColor: '#AF5',
        strokeWeight: 6,
      });

      marker.on('moving', (e) => {
        passedPolyline.setPath(e.passedPath);
        map.setCenter(e.target.getPosition(), true);
      });

      map.setFitView();

      const startAnimation = () => {
        console.log("2323233232")
        marker.moveAlong(lineArr, {
          duration: 500,
          autoRotation: true,
        });
      };

      const pauseAnimation = () => {
        marker.pauseMove();
      };

      const resumeAnimation = () => {
        marker.resumeMove();
      };

      const stopAnimation = () => {
        marker.stopMove();
      };

      // 将函数绑定到 window 对象上（或者你可以使用其他方式）
      window.startAnimation = startAnimation;
      window.pauseAnimation = pauseAnimation;
      window.resumeAnimation = resumeAnimation;
      window.stopAnimation = stopAnimation;

      // 保存引用到 useRef 中
      markerRef.current = marker;
      passedPolylineRef.current = passedPolyline;
    }).catch((e) => {
      console.error(e);
    });

  }, []); // 确保只在组件挂载时加载地图
  const createMap = async () => {
    const positions = [[116.405467, 39.907761], [116.415467, 39.907761], [116.415467, 39.917761], [116.425467, 39.907761],
    [116.385467, 39.907761]];
    const AMap = await AMapLoader.load({
      key: mapKey, // 高德地图key
      version: '2.0', // 指定API版本
      plugins: [
        'AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType',
        'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder'
      ], // 需要使用的插件
    });
    const map = new AMap.Map(mapContainerRef.current, mapOptions);
    // 地图初始化后的操作...
    // 如添加marker、添加事件监听等
    // onclick="clearMarker()
    var markerContent = '' +
      '<div class="custom-content-marker">' +
      '   <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">' +
      // '   <div class="close-btn" ">X</div>' +
      '</div>';
    // 示例：添加marker
    // const marker = new AMap.Marker({
    //   position: positions, // marker位置
    //   content: markerContent,
    //   // 以 icon 的 [center bottom] 为原点
    //   offset: new AMap.Pixel(0, 0)
    // });
    // map.add(marker); // 将marker添加到地图上
    const markers = []
    positions.forEach((item) => { 
      const marker = new AMap.Marker({
        position: item, // marker位置
        content: markerContent,
        // 以 icon 的 [center bottom] 为原点
        offset: new AMap.Pixel(0, 0)
      });
      map.add(marker);
      markers.push(marker);
    })
    // 示例：添加事件监听
    map.on('click', (e) => {
      console.log('地图被点击了', e);
      map.clearMap();
    });


    const marker = new AMap.Marker({
      map: map,
      position: [116.478935, 39.997761],
      icon: 'https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png',
      offset: new AMap.Pixel(-13, -26),
    });

    mapContainerRef.current = marker;
    const lineArr = [
      [116.478935, 39.997761],
      [116.478939, 39.997825],
      // ... 其他坐标点
      [116.484648, 39.999861],
    ];

    const polyline = new AMap.Polyline({
      map: map,
      path: lineArr,
      showDir: true,
      strokeColor: '#28F',
      strokeWeight: 6,
    });

    const passedPolyline = new AMap.Polyline({
      map: map,
      strokeColor: '#AF5',
      strokeWeight: 6,
    });
    passedPolylineRef.current = passedPolyline;
    marker.on('moving', (e) => {
      passedPolyline.setPath(e.passedPath);
      map.setCenter(e.target.getPosition(), true);
    });

    map.setFitView();



    const pauseAnimation = () => {
      marker.pauseMove();
    };

    const resumeAnimation = () => {
      marker.resumeMove();
    };

    const stopAnimation = () => {
      marker.stopMove();
    };


    //构造路线导航类
    // var driving = new AMap.Driving({
    //   map: map,
    //   panel: "panel"
    // });
    // // 根据起终点名称规划驾车导航路线
    // driving.search([
    //   { keyword: '北京市地震局(公交站)', city: '北京' },
    //   { keyword: '亦庄文化园(地铁站)', city: '北京' }
    // ], function (status, result) {
    //   // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
    //   if (status === 'complete') {
    //     // log.success('绘制驾车路线完成')
    //   } else {
    //     // log.error('获取驾车数据失败：' + result)
    //   }
    // });
    

  };


  // const startAnimation = () => {
  //   console.log("999999")
    // marker.moveAlong(lineArr, {
    //   duration: 500, // 可根据实际采集时间间隔设置
    //   autoRotation: true,
    // });
  // };
  return <>
    {/* <div className="input-card">
      <h4>轨迹回放控制</h4>
      <div className="input-item">
        <button className="btn" onClick={startAnimation}>开始动画</button>
        <button className="btn" onClick={window.pauseAnimation}>暂停动画</button>
      </div>
      <div className="input-item">
        <button className="btn" onClick={window.resumeAnimation}>继续动画</button>
        <button className="btn" onClick={window.stopAnimation}>停止动画</button>
      </div>
    </div>
    <div id={mapContainerId} ref={mapContainerRef} style={{ width: '100%', height: '100%' }} /> */}


    <div>
      <div
        ref={mapRef}
        style={{ height: '100vh', width: '100vw' }}
      />
      <div className="input-card" style={{ position: 'absolute', top: '10px', right: '10px', padding: '10px', backgroundColor: 'rgba(255, 255, 255, 0.8)', borderRadius: '5px' }}>
        <h4>轨迹回放控制</h4>
        <div className="input-item">
          <button className="btn" onClick={window.startAnimation}>开始动画</button>
          <button className="btn" onClick={window.pauseAnimation}>暂停动画</button>
        </div>
        <div className="input-item">
          <button className="btn" onClick={window.resumeAnimation}>继续动画</button>
          <button className="btn" onClick={window.stopAnimation}>停止动画</button>
        </div>
      </div>
      <style jsx>{`
        .input-card .btn {
          margin-right: 1.2rem;
          width: 9rem;
        }
        .input-card .btn:last-child {
          margin-right: 0;
        }
      `}</style>
    </div>
  </>
};

export default MapComponent;